#include "../ECS.h"
#include <algorithm>

namespace ECS
{
	mtBEGIN(Component)
	mtEND

	mtBEGIN(Assembly)
	mtEND

	Component::Component() : _assembly(nullptr)
	{

	}

	Component::~Component()
	{

	}

	Assembly* Component::getAssembly() const
	{
		return _assembly;
	}

	void Component::destroy()
	{
		getAssembly()->destroy(this);
	}

	void Assembly::sendMessage( TypeID messageID )
	{
		for (auto it = _components.begin(); it != _components.end(); ++it)
		{
			Component* component = *it;
			mtCALL_EX((component->getMetaTable()), component, messageID);
		}
	}

	Component* Assembly::getComponent( TypeID type ) const
	{
		for (auto it = _components.begin(); it != _components.end(); ++it)
		{
			Component* c = *it;
			if (c->getMetaTable()->isSubclass(type))
				return c;
		}

		return nullptr;
	}

	void Assembly::destroy( Component* component )
	{
		_components.erase(std::find(_components.begin(), _components.end(), component));
		delete component;
	}

	void Assembly::addComponent( Component* component )
	{
		component->_assembly = this;
		_components.push_back(component);
	}
}